var express = require('express')

var User = require('../models/User')
var router = express.Router()

// 统一返回格式
var responseData = null

// 中间件
router.use(function (req, res, next) {
  responseData = {
    code: 0,
    message: ''
  }
  next()
})

// 处理注册请求
router.post('/user/register', function (req, res, next) {
  // req.body是一个对象
  console.log('请求注册的请求体')
  console.log(req.body)
  var username = req.body.username
  var password = req.body.password
  var repassword = req.body.repassword

  if (!username) {
    responseData.code = 1
    responseData.message = '用户名不能为空'
    res.json(responseData)
    return
  }
  if (!password) {
    responseData.code = 2
    responseData.message = '密码不能为空'
    res.json(responseData)
    return
  }
  if (password !== repassword) {
    responseData.code = 3
    responseData.message = '两次输入的密码不一致'
    res.json(responseData)
    return
  }
  // 判断用户名是否被注册了
  User.findOne({
    username: username
  }).then(function (userInfo) {
    if (userInfo) {
      responseData.code = 4
      responseData.message = '用户名已经被注册了'
      res.json(responseData)
      return
    }
    var user = new User({
      username: username,
      password: password
    })
    return user.save()
  }).then(function (newUserInfo) {
    console.log(newUserInfo)
    responseData.message = '注册成功'
    res.json(responseData)
  })



})

// 处理登录请求
router.post('/user/login', function (req, res, next) {
  console.log('请求登录的请求体')
  console.log(req.body)
  var username = req.body.username
  var password = req.body.password
  if (username == '' || password == '') {
    responseData.code = 1
    responseData.message = '用户名和密码不能为空'
    res.json(responseData)
    return
  }
  User.findOne({
    username: username,
    password: password
  }).then(function (userInfo) {
    if (!userInfo) {
      responseData.code = 2
      responseData.message = '用户名或者密码错误'
      res.json(responseData)
      return
    }
    responseData.message = '登录成功'
    responseData.userInfo = {
      id: userInfo.id,
      username: userInfo.username
    }
    // 设置cookie
    req.cookies.set('userInfo', JSON.stringify({
      _id: userInfo._id,
      username: userInfo.username
    }))

    res.json(responseData)
    return
  })
})
// 处理退出请求
router.get('/user/logout', function (req, res) {
  req.cookies.set('userInfo', null);
  res.json(responseData);
})

module.exports = router